package com.share.drools.state;

import lombok.Getter;
import lombok.NoArgsConstructor;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 * @author caifan
 * @created 2021/4/2
 * description:
 */
@Getter
@NoArgsConstructor
public class State {
    public static final int NOTRUN = 0;
    public static final int FINISHED = 1;

    private final PropertyChangeSupport changes = new PropertyChangeSupport(this);

    private String name;
    private int state;

    public State(final String name) {
        this.name = name;
        this.state = State.NOTRUN;
    }

    public void setState(final int newState) {
        final int oldState = this.state;
        this.state = newState;
        this.changes.firePropertyChange("state", oldState, newState);
    }

    public boolean inState(final String name, final int state) {
        return this.name.equals(name) && this.state == state;
    }

    @Override
    public String toString() {
        switch ( this.state ) {
            case NOTRUN :
                return this.name + "[" + "NOTRUN" + "]";
            case FINISHED :
            default :
                return this.name + "[" + "FINISHED" + "]";
        }
    }

    public void addPropertyChangeListener(final PropertyChangeListener l) {
        this.changes.addPropertyChangeListener( l );
    }

    public void removePropertyChangeListener(final PropertyChangeListener l) {
        this.changes.removePropertyChangeListener( l );
    }
}
